import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import user from '@/utils/auth'


const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000,// request timeout
  headers: { "Content-Type": "application/json;charset=utf-8" },
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (user.getToken()) {
      config.headers.Authorization = user.getToken()
    }

    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log(response,'response');
    const { code, msg } = response.data;
    if (code == '00000' || code == 200) {
      return response.data
    } else {
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      Message({
        message: msg || 'System error, please contact the administrator',
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject(new Error(msg || 'Error'));
    }

  },
  error => {
    console.log(error, 'err');
    if (error.response.data) {
      const { code, msg } = error.response.data;
      if (code === 'A0230') {
        user.removeToken();
        MessageBox.confirm(
          'Your login status has expired. You can continue to stay on this page or log in again!',
          'SYSTEM PROMPT',
          {
            confirmButtonText: 'Log In Again',
            cancelButtonText: 'CANCEL',
            type: 'warning'
          }
        ).then(() => {
          location.href = '/#/Login'
        })
      }
    } else {
      Message({
        message: 'System error, please contact the administrator',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }
)

export default service
